<template>
  <div id='wrap'>
    <h1>计算属性</h1>
    <div>
        在模板中计算：{{ author.books.length>1 ? author.books.join('_') : author.books[0] }}
    </div>
    <input type="text" v-model="bookName">
    <button @click="addNewBook">新增一本暴富秘籍</button>
    <hr>
    <div v-for="item in 3">
        <p>{{ funcBooksStr() }}</p>
    </div>
    <hr>
    <div v-for="item in 3">
        <p>{{ compBooksStr }}</p>
    </div>
    <hr>
    <p>用户全名(只读计算属性):{{ fullName }}</p>
    <button @click="edit">改变</button>
    <hr>
    <p>用户全名(可写计算属性):{{ fullName1 }}</p>
    <input type="text" v-model="fullName1">
  </div>
</template>

<script lang='ts'>
export default {
  name: 'scu11',
}
</script>

<script lang='ts' setup>
import { ref,reactive,computed } from 'vue'
const bookName=ref('')
const author=reactive({
    name:'john doe',
    books:['西游记','水浒传','三国演义','红楼梦']
})
const addNewBook=()=>{
    try{
        if(!bookName){
        throw new Error("请输入书的名字");
        }
        console.log('模拟计算属性');
        author.books.push(bookName.value)
    }catch(error:any){
        console.log(error.msg);
    }
}
const books=reactive(['Book A','Book B','Book C'])
const funcBooksStr=function(){
    return books.length>1 ? books.join('_') : books[0]
}
const compBooksStr=computed(()=>{
    return books.length>1 ? books.join('_') : books[0]
})
const user=reactive({
    firstName:'小明',
    lastName:'小红'
})
const fullName=computed(()=>{
    console.log('触发计算');
    return `${user.firstName} ${user.lastName}`
})
const edit=()=>{
    user.firstName='小刚'
}
const fullName1=computed({
    get:()=>`${user.firstName} ${user.lastName}`,
    set:(value:string)=>{
        console.log('计算属性重新计算111');
        const [firstName,lastName]=value.split('')
        user.firstName=firstName
        user.lastName=lastName
    }
})
</script>

<style scoped lang='scss'>
h1{
    color: #333;
}
p{
    margin: 8px 0; 
}
</style>